package gaboli.common.xml;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.HashMap;
import java.util.Map;

/**
 * Custom Adapter for Maps. Code adapted from sources found at http://stackoverflow
 * .com/questions/3941479/jaxb-how-to-marshall-map-into-keyvalue-key
 * and at http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/.
 * @author C. Burrell deltafront@gmail.com
 */
public class ElementMapperAdapter extends XmlAdapter<ElementMapper[], Map<Object, Object>>
{

    @Override
    public ElementMapper[] marshal( Map<Object, Object> map ) throws Exception
    {
        ElementMapper[] mapElements = new ElementMapper[ map.size() ];
        int i = 0;
        for( Map.Entry<Object, Object> entry : map.entrySet() )
        {
            mapElements[ i ] = new ElementMapper( entry.getKey(), entry.getValue() );
            i++;
        }
        return mapElements;
    }

    @Override
    public Map<Object, Object> unmarshal( ElementMapper[] elementMapperArray ) throws Exception
    {
        Map<Object, Object> r = new HashMap<Object, Object>();
        for( ElementMapper mapelement : elementMapperArray )
        {
            r.put( mapelement.key, mapelement.value );
        }
        return r;
    }
}
